﻿using Microsoft.Phone.Controls;
using System;
using System.Windows.Navigation;
using WaitLess.App.Services.Interfaces;

namespace WaitLess.App.Views
{
    public partial class FoursquarePage : PhoneApplicationPageBase
    {
        private readonly INavigationService _navigationService;
        private readonly IDataCache _dataCache;
        private Uri _redirectUri;

        public FoursquarePage()
        {
            InitializeComponent();

            _navigationService = ContainerInitializer.Get<INavigationService>();
            _dataCache = ContainerInitializer.Get<IDataCache>();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (!e.Uri.ToString().Contains("redirect"))
                return;

            var redirect = e.Uri.ToString().Substring(e.Uri.ToString().IndexOf("=") + 1);   //on the fly solution :)

            _redirectUri = new Uri(redirect, UriKind.Relative);
        }

        private void loaded_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            LoadFoursquareOAuthPage();
        }

        private void LoadFoursquareOAuthPage()
        {
            var url = string.Format("https://foursquare.com/oauth2/authenticate?client_id={0}&response_type=token&redirect_uri={1}",
                Settings.FoursquareClientId, Settings.FoursquareRedirectUri);

            browser.IsScriptEnabled = true;
            browser.Navigating += browser_Navigating;
            browser.Navigate(new Uri(url, UriKind.Absolute));
        }

        private void browser_Navigating(object sender, NavigatingEventArgs e)
        {
            if (!e.Uri.ToString().Contains("#access_token="))
                return;

            var responseUrl = string.Format("{0}#access_token=", Settings.FoursquareRedirectUri);
            var accessToken = e.Uri.ToString().Replace(responseUrl, string.Empty);
            _dataCache.FoursquareAccessToken = accessToken;
            
            if (_redirectUri != null)
                _navigationService.Navigate(_redirectUri);
            else
                _navigationService.NavigateToMainPage();
        }
    }
}